from flask import request, jsonify
from app.models import User, Video, Like, Favorite, Follow, db
from sqlalchemy import func


def get_current_user():
    """
    获取当前登录用户的详细信息
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 查询用户
        user = User.query.get(user_id)
        
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在',
                'data': None
            }), 404
        
        # 返回用户信息
        return jsonify({
            'code': 200,
            'message': '获取用户信息成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'bio': user.bio,
                'location': user.location,
                'created_at': user.created_at.isoformat() + 'Z' if user.created_at else None,
                'updated_at': user.updated_at.isoformat() + 'Z' if user.updated_at else None
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户信息失败: {str(e)}',
            'data': None
        }), 500


def update_current_user():
    """
    更新当前登录用户的个人信息
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 获取请求数据
        data = request.get_json()
        
        # 查询用户
        user = User.query.get(user_id)
        
        if not user:
            return jsonify({
                'code': 404,
                'message': '用户不存在',
                'data': None
            }), 404
        
        # 更新用户信息
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'avatar' in data:
            user.avatar = data['avatar']
        if 'bio' in data:
            user.bio = data['bio']
        if 'location' in data:
            user.location = data['location']
        
        # 保存到数据库
        db.session.commit()
        
        # 返回更新后的用户信息
        return jsonify({
            'code': 200,
            'message': '更新用户信息成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'bio': user.bio,
                'location': user.location,
                'updated_at': user.updated_at.isoformat() + 'Z' if user.updated_at else None
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 400,
            'message': f'请求参数错误: {str(e)}',
            'data': None
        }), 400


def get_user_stats():
    """
    获取当前登录用户的统计信息
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 查询用户点赞的视频数量
        like_count = Like.query.filter_by(user_id=user_id).count()
        
        # 查询用户的粉丝数量
        follower_count = Follow.query.filter_by(followed_id=user_id).count()
        
        # 查询用户发布的视频获得的点赞总数
        video_like_count = db.session.query(func.sum(Video.like_count)).filter_by(user_id=user_id).scalar() or 0
        
        # 返回统计信息
        return jsonify({
            'code': 200,
            'message': '获取用户统计信息成功',
            'data': {
                'likeCount': like_count,
                'followerCount': follower_count,
                'videoLikeCount': int(video_like_count)
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户统计信息失败: {str(e)}',
            'data': None
        }), 500


def get_user_videos():
    """
    获取当前登录用户发布的视频列表
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        
        # 查询用户发布的视频
        query = Video.query.filter_by(user_id=user_id, status=1)
        pagination = query.order_by(Video.created_at.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        videos = pagination.items
        total = pagination.total
        
        # 格式化视频数据
        video_list = []
        for video in videos:
            video_list.append({
                'id': video.id,
                'title': video.title,
                'cover_url': video.cover_url,
                'video_url': video.video_url,
                'description': video.description,
                'view_count': video.view_count,
                'like_count': video.like_count,
                'coin_count': video.coin_count,
                'share_count': video.share_count,
                'category_id': video.category_id,
                'category_name': video.category.name if video.category else None,
                'created_at': video.created_at.isoformat() + 'Z' if video.created_at else None
            })
        
        # 返回视频列表
        return jsonify({
            'code': 200,
            'message': '获取用户发布视频列表成功',
            'data': {
                'total': total,
                'page': page,
                'pageSize': page_size,
                'videos': video_list
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户视频列表失败: {str(e)}',
            'data': None
        }), 500


def get_user_favorites():
    """
    获取当前登录用户收藏的视频列表
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        
        # 查询用户收藏的视频
        query = Video.query.join(
            Favorite, Video.id == Favorite.video_id
        ).filter(
            Favorite.user_id == user_id, Video.status == 1
        )
        pagination = query.order_by(Video.created_at.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        videos = pagination.items
        total = pagination.total
        
        # 格式化视频数据
        favorite_list = []
        for video in videos:
            favorite = Favorite.query.filter_by(
                user_id=user_id, video_id=video.id
            ).first()
            favorite_list.append({
                'id': video.id,
                'title': video.title,
                'cover_url': video.cover_url,
                'video_url': video.video_url,
                'description': video.description,
                'view_count': video.view_count,
                'like_count': video.like_count,
                'coin_count': video.coin_count,
                'share_count': video.share_count,
                'category_id': video.category_id,
                'category_name': video.category.name if video.category else None,
                'created_at': video.created_at.isoformat() + 'Z' if video.created_at else None,
                'favorited_at': favorite.created_at.isoformat() + 'Z' if favorite.created_at else None
            })
        
        # 返回收藏列表
        return jsonify({
            'code': 200,
            'message': '获取用户收藏视频列表成功',
            'data': {
                'total': total,
                'page': page,
                'pageSize': page_size,
                'favorites': favorite_list
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户收藏列表失败: {str(e)}',
            'data': None
        }), 500


def get_user_likes():
    """
    获取当前登录用户点赞的视频列表
    
    Returns:
        JSON响应
    """
    try:
        # 从请求上下文中获取用户ID
        user_id = request.current_user_id
        
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        
        # 查询用户点赞的视频
        query = Video.query.join(
            Like, Video.id == Like.video_id
        ).filter(
            Like.user_id == user_id, Video.status == 1
        )
        pagination = query.order_by(Video.created_at.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        videos = pagination.items
        total = pagination.total
        
        # 格式化视频数据
        like_list = []
        for video in videos:
            like = Like.query.filter_by(
                user_id=user_id, video_id=video.id
            ).first()
            like_list.append({
                'id': video.id,
                'title': video.title,
                'cover_url': video.cover_url,
                'video_url': video.video_url,
                'description': video.description,
                'view_count': video.view_count,
                'like_count': video.like_count,
                'coin_count': video.coin_count,
                'share_count': video.share_count,
                'category_id': video.category_id,
                'category_name': video.category.name if video.category else None,
                'created_at': video.created_at.isoformat() + 'Z' if video.created_at else None,
                'liked_at': like.created_at.isoformat() + 'Z' if like.created_at else None
            })
        
        # 返回点赞列表
        return jsonify({
            'code': 200,
            'message': '获取用户点赞视频列表成功',
            'data': {
                'total': total,
                'page': page,
                'pageSize': page_size,
                'likes': like_list
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取用户点赞列表失败: {str(e)}',
            'data': None
        }), 500